<template>
  <div class="catalog-product-image-batch">
    <!-- 触发按钮 -->
    <el-button
      :type="buttonType"
      :size="buttonSize"
      :icon="buttonIcon"
      :disabled="disabled"
      style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
      @click="showDialog"
    >
      {{ buttonText }}
    </el-button>

    <!-- 步骤式向导对话框 -->
    <el-dialog
      title="根据目录册批量生成产品图片"
      :visible.sync="dialogVisible"
      width="80%"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <!-- 步骤指示器 -->
      <el-steps :active="currentStep" finish-status="success" align-center style="margin-bottom: 30px;">
        <el-step title="输入目录册" icon="el-icon-edit" />
        <el-step title="选择图片" icon="el-icon-picture" />
        <el-step title="选择模板" icon="el-icon-picture-outline-round" />
        <el-step title="批量渲染" icon="el-icon-loading" />
        <el-step title="完成应用" icon="el-icon-check" />
      </el-steps>

      <!-- 步骤内容 -->
      <div class="step-content">
        <!-- 步骤1: 输入目录册Token/ID -->
        <div v-if="currentStep === 0" class="step-panel">
          <div class="step-description">
            <i class="el-icon-info" style="color: #409EFF;" />
            请输入目录册的Token或ID，系统将自动查询该目录册下的所有产品图片
          </div>
          <el-form label-width="120px">
            <el-form-item label="目录册Token/ID">
              <el-input
                v-model="tokenOrId"
                placeholder="请输入目录册Token（如：abc123）或ID（如：456）"
                clearable
                @keyup.enter.native="handleQueryQuote"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 步骤2: 选择图片 -->
        <div v-if="currentStep === 1" class="step-panel">
          <div class="step-description">
            <i class="el-icon-success" style="color: #67C23A;" />
            已找到目录册 <strong>{{ quoteData.quote_name }}</strong>，包含 <strong>{{ quoteData.total_images }}</strong> 张图片，请选择需要渲染的图片
          </div>
          <div class="image-selection-area">
            <div class="selection-header">
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              >
                全选 (已选 {{ selectedImages.length }} / {{ quoteData.images.length }})
              </el-checkbox>
            </div>
            <el-checkbox-group v-model="selectedImages" @change="handleCheckedImagesChange">
              <div class="image-grid">
                <div
                  v-for="(img, index) in quoteData.images"
                  :key="index"
                  class="image-checkbox-item"
                >
                  <el-checkbox :key="img" :label="img">
                    <el-image
                      :src="img"
                      fit="cover"
                      class="preview-image"
                      :preview-src-list="quoteData.images"
                      :initial-index="index"
                    >
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline" />
                      </div>
                    </el-image>
                  </el-checkbox>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </div>

        <!-- 步骤3: 选择模板 -->
        <div v-if="currentStep === 2" class="step-panel">
          <div class="step-description">
            <i class="el-icon-info" style="color: #409EFF;" />
            选择渲染效果模板（可选），或直接点击"下一步"使用默认样式
          </div>
          <div class="template-selection-area">
            <div class="template-header">
              <span>可用模板</span>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                style="color: #1EB7E6;"
                @click="showTemplateDialog"
              >
                添加新模板
              </el-button>
            </div>
            <div v-if="templates && templates.length > 0" class="template-list">
              <div
                v-for="template in templates"
                :key="template.id"
                class="template-item"
                :class="{ 'selected': selectedTemplateId === template.id }"
                @click="selectedTemplateId = template.id"
              >
                <el-image
                  :src="template.image_url"
                  fit="cover"
                  class="template-image"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" />
                  </div>
                </el-image>
                <div class="template-info">
                  <div class="template-name">{{ template.name }}</div>
                </div>
                <div v-if="selectedTemplateId === template.id" class="selected-badge">
                  <i class="el-icon-check" />
                </div>
              </div>
              <div
                class="template-item no-template"
                :class="{ 'selected': selectedTemplateId === null }"
                @click="selectedTemplateId = null"
              >
                <div class="no-template-content">
                  <i class="el-icon-close" />
                  <p>不使用模板</p>
                </div>
                <div v-if="selectedTemplateId === null" class="selected-badge">
                  <i class="el-icon-check" />
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无模板，点击右上角添加" :image-size="80" />
          </div>
        </div>

        <!-- 步骤4: 批量渲染中 -->
        <div v-if="currentStep === 3" class="step-panel">
          <div class="rendering-progress">
            <div class="progress-header">
              <i class="el-icon-loading" />
              正在批量渲染图片...
            </div>
            <el-progress
              :percentage="renderProgress"
              :status="renderProgress === 100 ? 'success' : ''"
              :stroke-width="20"
            />
            <div class="progress-text">
              {{ renderStatus }}
            </div>
            <div v-if="renderLog" class="render-log">
              <div v-for="(log, index) in renderLog" :key="index" class="log-item">
                <i :class="log.success ? 'el-icon-success' : 'el-icon-error'" :style="{color: log.success ? '#67C23A' : '#F56C6C'}" />
                {{ log.message }}
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤5: 完成 -->
        <div v-if="currentStep === 4" class="step-panel">
          <div class="step-description success-message">
            <i class="el-icon-success" style="color: #67C23A; font-size: 48px;" />
            <h3>渲染完成！</h3>
            <p>成功渲染 <strong>{{ renderResults.success_count }}</strong> 张图片
              <span v-if="renderResults.failed_count > 0">，失败 <strong style="color: #F56C6C;">{{ renderResults.failed_count }}</strong> 张</span>
            </p>
          </div>
          <div class="result-preview">
            <div class="result-header">渲染结果预览</div>
            <div class="result-grid">
              <div
                v-for="(item, index) in renderResults.rendered_images"
                :key="index"
                class="result-item"
              >
                <el-image
                  :src="item.rendered"
                  fit="cover"
                  class="result-image"
                  :preview-src-list="renderResults.all_rendered_urls"
                  :initial-index="index"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" />
                  </div>
                </el-image>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 对话框底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="currentStep > 0 && currentStep < 3" @click="prevStep">上一步</el-button>
        <el-button
          v-if="currentStep === 0"
          type="primary"
          :loading="loading"
          :disabled="!tokenOrId"
          @click="handleQueryQuote"
        >
          查询目录册
        </el-button>
        <el-button
          v-if="currentStep === 1"
          type="primary"
          :disabled="selectedImages.length === 0"
          @click="nextStep"
        >
          下一步 ({{ selectedImages.length }} 张图片)
        </el-button>
        <el-button
          v-if="currentStep === 2"
          type="primary"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          @click="startBatchRender"
        >
          开始渲染
        </el-button>
        <el-button
          v-if="currentStep === 4"
          type="success"
          @click="applyToPage"
        >
          应用到页面
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加模板对话框 -->
    <el-dialog
      title="添加模板"
      :visible.sync="templateDialogVisible"
      width="500px"
      :append-to-body="true"
    >
      <el-form :model="newTemplate" label-width="100px">
        <el-form-item label="模板名称" required>
          <el-input v-model="newTemplate.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="图片URL" required>
          <el-input
            v-model="newTemplate.image_url"
            type="textarea"
            :rows="3"
            placeholder="请输入模板图片URL"
          />
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input
            v-model="newTemplate.description"
            type="textarea"
            :rows="2"
            placeholder="请输入模板描述（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="templateDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          @click="addTemplate"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetQuoteImages, BatchRenderCatalogImages } from '@/api/crm/catalogbatch'
import { Get as GetTemplates, Post as CreateTemplate } from '@/api/crm/crmcatalogimagetemplate'
import { Get as GetCatalogImages } from '@/api/crm/crmcatalogimage'

export default {
  name: 'CatalogProductImageBatch',
  props: {
    buttonText: {
      type: String,
      default: '根据目录册批量生成'
    },
    buttonType: {
      type: String,
      default: 'primary'
    },
    buttonSize: {
      type: String,
      default: 'small'
    },
    buttonIcon: {
      type: String,
      default: 'el-icon-s-grid'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      currentStep: 0, // 0-4 对应5个步骤

      // 步骤1数据
      tokenOrId: '',

      // 步骤2数据
      quoteData: {
        quote_id: null,
        quote_name: '',
        quote_token: '',
        total_images: 0,
        images: []
      },
      selectedImages: [],
      checkAll: false,
      isIndeterminate: false,

      // 步骤3数据
      templates: [],
      selectedTemplateId: null,
      templateDialogVisible: false,
      newTemplate: {
        name: '',
        image_url: '',
        description: ''
      },

      // 步骤4数据
      renderProgress: 0,
      renderStatus: '',
      renderLog: [],

      // 步骤5数据
      renderResults: {
        total: 0,
        success_count: 0,
        failed_count: 0,
        rendered_images: [],
        failed_images: [],
        main_image: null,
        all_rendered_urls: []
      },

      // 已有的生成图片
      existingImages: []
    }
  },
  methods: {
    showDialog() {
      this.dialogVisible = true
      this.loadTemplates()
    },

    handleClose() {
      this.dialogVisible = false
      this.resetData()
    },

    resetData() {
      this.currentStep = 0
      this.tokenOrId = ''
      this.quoteData = {
        quote_id: null,
        quote_name: '',
        quote_token: '',
        total_images: 0,
        images: []
      }
      this.selectedImages = []
      this.checkAll = false
      this.isIndeterminate = false
      this.selectedTemplateId = null
      this.renderProgress = 0
      this.renderStatus = ''
      this.renderLog = []
      this.renderResults = {
        total: 0,
        success_count: 0,
        failed_count: 0,
        rendered_images: [],
        failed_images: [],
        main_image: null,
        all_rendered_urls: []
      }
      this.existingImages = []
    },

    // 步骤1: 查询目录册
    async handleQueryQuote() {
      if (!this.tokenOrId) {
        this.$message.warning('请输入目录册Token或ID')
        return
      }

      this.loading = true
      try {
        const response = await GetQuoteImages({ token_or_id: this.tokenOrId })
        if (response.success) {
          this.quoteData = response.data

          // 查询该目录册是否有已生成的图片
          await this.checkExistingImages()

          // 如果有已生成的图片，询问用户是使用已有图片还是重新生成
          if (this.existingImages.length > 0) {
            this.$confirm(
              `该目录册已有 ${this.existingImages.length} 张生成的图片，是否直接使用？`,
              '发现已有图片',
              {
                confirmButtonText: '使用已有图片',
                cancelButtonText: '重新生成',
                type: 'info',
                distinguishCancelAndClose: true
              }
            ).then(() => {
              // 用户选择使用已有图片，直接跳到步骤5
              this.useExistingImages()
            }).catch((action) => {
              // action可能是'cancel'（点击重新生成按钮）或'close'（点击X关闭）
              if (action === 'cancel') {
                // 用户选择重新生成，进入步骤2
                this.currentStep = 1
                this.$message.info('请选择要渲染的图片')
              } else {
                // 用户点击X关闭，重置状态
                this.tokenOrId = ''
                this.quoteData = {
                  quote_id: null,
                  quote_name: '',
                  quote_token: '',
                  total_images: 0,
                  images: []
                }
                this.existingImages = []
              }
            })
          } else {
            // 没有已生成的图片，直接进入步骤2
            this.currentStep = 1
            this.$message.success(response.msg)
          }
        } else {
          this.$message.error(response.msg || '查询失败')
        }
      } catch (error) {
        console.error('查询目录册失败:', error)
        this.$message.error('查询失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },

    // 查询该目录册已有的生成图片
    async checkExistingImages() {
      if (!this.quoteData.quote_id) {
        return
      }

      try {
        const response = await GetCatalogImages(null, `quote_id=${this.quoteData.quote_id}`)
        if (response.success && response.data && response.data.data) {
          this.existingImages = response.data.data
            .filter(item => item.result_image_url && item.status === 'completed')
            .map(item => ({
              id: item.id,
              url: item.result_image_url,
              name: item.name || '目录册图片',
              created_at: item.create_at
            }))
        }
      } catch (error) {
        console.error('查询已有图片失败:', error)
      }
    },

    // 使用已有图片（跳过步骤2-4，直接到步骤5）
    useExistingImages() {
      // 将已有图片填充到renderResults
      this.renderResults = {
        total: this.existingImages.length,
        success_count: this.existingImages.length,
        failed_count: 0,
        rendered_images: this.existingImages.map((img, index) => ({
          index: index,
          original: '',
          rendered: img.url,
          catalog_image_id: img.id
        })),
        failed_images: [],
        main_image: this.existingImages[0]?.url || null,
        all_rendered_urls: this.existingImages.map(img => img.url)
      }

      // 直接跳到步骤5
      this.currentStep = 4
      this.$message.success('已加载已有图片，可以直接应用到页面')
    },

    // 步骤2: 图片选择
    handleCheckAllChange(val) {
      this.selectedImages = val ? this.quoteData.images.slice() : []
      this.isIndeterminate = false
    },

    handleCheckedImagesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.quoteData.images.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.quoteData.images.length
    },

    // 步骤导航
    nextStep() {
      if (this.currentStep < 4) {
        this.currentStep++
      }
    },

    prevStep() {
      if (this.currentStep > 0) {
        this.currentStep--
      }
    },

    // 步骤3: 加载模板列表
    async loadTemplates() {
      try {
        const response = await GetTemplates()
        if (response.success) {
          this.templates = response.data || []
        }
      } catch (error) {
        console.error('加载模板列表失败:', error)
      }
    },

    // 显示添加模板对话框
    showTemplateDialog() {
      this.newTemplate = {
        name: '',
        image_url: '',
        description: ''
      }
      this.templateDialogVisible = true
    },

    // 添加模板
    async addTemplate() {
      if (!this.newTemplate.name) {
        this.$message.warning('请输入模板名称')
        return
      }
      if (!this.newTemplate.image_url) {
        this.$message.warning('请输入模板图片URL')
        return
      }

      try {
        const response = await CreateTemplate(this.newTemplate)
        if (response.success) {
          this.$message.success('模板添加成功')
          this.templateDialogVisible = false
          await this.loadTemplates()
        } else {
          this.$message.error(response.msg || '添加失败')
        }
      } catch (error) {
        console.error('添加模板失败:', error)
        this.$message.error('添加失败')
      }
    },

    // 步骤4: 开始批量渲染
    async startBatchRender() {
      this.currentStep = 3
      this.renderProgress = 0
      this.renderStatus = '正在准备渲染...'
      this.renderLog = []

      try {
        // 准备请求数据
        const requestData = {
          quote_id: this.quoteData.quote_id,
          images: this.selectedImages
        }

        if (this.selectedTemplateId) {
          requestData.template_id = this.selectedTemplateId
        }

        this.renderLog.push({
          success: true,
          message: `开始渲染 ${this.selectedImages.length} 张图片...`
        })

        this.renderProgress = 10
        this.renderStatus = '正在调用AI批量渲染...'

        // 调用批量渲染API（同步）
        const response = await BatchRenderCatalogImages(requestData)

        if (response.success) {
          this.renderProgress = 100
          this.renderStatus = '渲染完成！'
          this.renderResults = response.data

          // 添加成功日志
          this.renderLog.push({
            success: true,
            message: `成功渲染 ${response.data.success_count} 张图片`
          })

          // 添加失败日志
          if (response.data.failed_count > 0) {
            response.data.failed_images.forEach((failed, index) => {
              this.renderLog.push({
                success: false,
                message: `第 ${failed.index + 1} 张图片渲染失败: ${failed.error}`
              })
            })
          }

          this.$message.success(response.msg)

          // 延迟跳转到下一步
          setTimeout(() => {
            this.currentStep = 4
          }, 1000)
        } else {
          throw new Error(response.msg || '渲染失败')
        }
      } catch (error) {
        console.error('批量渲染失败:', error)
        const errorMsg = error.response && error.response.data && error.response.data.msg
          ? error.response.data.msg
          : error.message || '未知错误'

        this.renderLog.push({
          success: false,
          message: `渲染失败: ${errorMsg}`
        })

        this.$message.error('渲染失败: ' + errorMsg)
        this.renderProgress = 0
        this.renderStatus = '渲染失败'
      }
    },

    // 步骤5: 应用到页面
    applyToPage() {
      if (this.renderResults.all_rendered_urls && this.renderResults.all_rendered_urls.length > 0) {
        this.$emit('apply', {
          main_image: this.renderResults.main_image,
          gallery_images: this.renderResults.all_rendered_urls,
          gallery_text: this.renderResults.all_rendered_urls.join('\n')
        })
        this.$message.success('已应用到页面')
        this.handleClose()
      } else {
        this.$message.warning('没有可应用的图片')
      }
    }
  }
}
</script>

<style scoped>
.catalog-product-image-batch {
  display: inline-block;
}

.step-content {
  min-height: 400px;
  padding: 20px;
}

.step-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.step-description {
  padding: 15px;
  background-color: #f0f9ff;
  border-left: 4px solid #409EFF;
  border-radius: 4px;
  color: #303133;
  line-height: 1.6;
}

.step-description.success-message {
  background-color: #f0f9ff;
  border-left-color: #67C23A;
  text-align: center;
  padding: 30px;
}

.step-description.success-message h3 {
  margin: 15px 0;
  color: #303133;
}

.step-description.success-message p {
  color: #606266;
  font-size: 16px;
}

/* 图片选择区域 */
.image-selection-area {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafbfc;
}

.selection-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.image-checkbox-item >>> .el-checkbox {
  display: block;
  width: 100%;
}

.image-checkbox-item >>> .el-checkbox__label {
  display: block;
  width: 100%;
  padding: 0;
}

.preview-image {
  width: 100%;
  height: 120px;
  border-radius: 4px;
  cursor: pointer;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #c0c4cc;
  font-size: 28px;
}

/* 模板选择区域 */
.template-selection-area {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafbfc;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 600;
}

.template-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.template-item {
  position: relative;
  border: 2px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.template-item:hover {
  border-color: #1EB7E6;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(30, 183, 230, 0.2);
}

.template-item.selected {
  border-color: #1EB7E6;
  box-shadow: 0 0 8px rgba(30, 183, 230, 0.4);
}

.template-image {
  width: 100%;
  height: 120px;
}

.template-info {
  padding: 8px;
  border-top: 1px solid #e4e7ed;
  background-color: #fff;
}

.template-name {
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.selected-badge {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  background-color: #1EB7E6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.no-template {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 120px;
}

.no-template-content {
  text-align: center;
  color: #909399;
}

.no-template-content i {
  font-size: 48px;
  display: block;
  margin-bottom: 10px;
}

.no-template-content p {
  margin: 0;
  font-size: 14px;
}

/* 渲染进度区域 */
.rendering-progress {
  text-align: center;
  padding: 30px;
}

.progress-header {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.progress-header i {
  color: #1EB7E6;
  margin-right: 8px;
}

.progress-text {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
}

.render-log {
  margin-top: 30px;
  max-height: 300px;
  overflow-y: auto;
  text-align: left;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
}

.log-item {
  padding: 8px 0;
  line-height: 1.5;
  border-bottom: 1px solid #ebeef5;
}

.log-item:last-child {
  border-bottom: none;
}

.log-item i {
  margin-right: 8px;
}

/* 结果预览区域 */
.result-preview {
  margin-top: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafbfc;
}

.result-header {
  font-weight: 600;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.result-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.result-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
}

.result-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-image {
  width: 100%;
  height: 150px;
  cursor: pointer;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
